import { useState, useEffect, useContext, useCallback, useRef } from 'react'
import { Button, Collapse, Menu, Tooltip, Tree } from 'antd';
import PubSub from 'pubsub-js';
import _ from 'lodash';
import { Group } from 'ol/layer';
import { Circle, Text as TextStyle, Icon } from 'ol/style';
import Style from 'ol/style/Style';
import Stroke from 'ol/style/Stroke';
import Fill from 'ol/style/Fill';
import FxqhContext from './fxqhContext';
import PanelLeft from '../../../../../common/PanelLeft';
import DarkBtn from '../../../../../common/DarkBtn';
import DarkCard from '../../../../../common/DarkCard';
import useBusinessMap from '../../../../../common/BusinessMap/useBusinessMap';
import { createBaseLayers, createLayer, dataToFeature, navByWkt } from '../../../../../../utils/helper/mapHelper';
import { LeftOutlined, MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import JcyjApi from '../../../../../../utils/apis/JcyjApi';
import Example from '../../Jcyj/example';
import { resourcePath } from '../../../../../../utils/resource';
import Yhdzzt from './Yhdzzt';
import Lndzsjlb from './Lndzsjlb';
import Yhhltb from './Yhhltb';
import Yhslhz from './Yhslhz';
import StatisticAndList from '../StatisticAndList';
import DisasterDetails from '../StatisticAndList/DisasterDetails';
import FxqyApi from '../../../../../../utils/apis/FxqyApi';
import { Feature, Overlay } from 'ol';
import bootstrap from 'bootstrap/dist/js/bootstrap.bundle';
import { feature } from 'caniuse-lite';




const generateData = (datas, dl) => {
    datas.forEach(data => {
        data.dl = dl;
        if (data.children) {
            generateData(data.children, dl)
        }
    });
    return datas
}

function Popup({ title, position }) {



    return (

        <div style={{
            position: 'absolute',
            left: `${position.x}px`,
            top: `${position.y - 50}px`,
            display: 'inline-block',
            whiteSpace: 'nowrap',
            borderRadius: 10,/* 设置圆角半径 */
            backgroundColor: 'black', /* 设置背景色为黑色 */
            padding: 10, /* 可选：添加内边距以增加可读性 */
            color: 'white',
        }}>{title} </div>

    );
}

export default function SpecialMap(props) {

    const { setJyl } = props
    // const { layerDatas } = useContext(GlobalContext)
    const [visible, setVisible] = useState(true);
    const map = useBusinessMap();
    const [baseGroupLayers, setBaseGroupLayers] = useState();
    const [legendDatas, setLegendDatas] = useState();

    const [detailSwitch, setDetailSwitch] = useState();
    const [StatisticAndListSwitch, setStatisticAndListSwitch] = useState();
    const [leftKey, setLeftKey] = useState();
    const [rowData, setRowData] = useState();
    const [disasterType, setDisasterType] = useState();
    const [targetTemplate, setTargetTemplate] = useState();
    const [layers, setLayers] = useState();

    const [selectedName, setSelectedName] = useState();

    const [position, setPosition] = useState({ x: 0, y: 0 });

    useEffect(() => {
        const handleMouseMove = (event) => {
            setPosition({ x: event.pageX, y: event.pageY });

        };

        window.addEventListener('mousemove', handleMouseMove);

        return () => {
            window.removeEventListener('mousemove', handleMouseMove);
        };
    }, []);

    useEffect(() => {

        if (map) {
            const handler = evt => {

                /* 
                --features获取的地图要素需要过滤，为了实现效果，现只读取了要素第一个
                */
                const features = map.getFeaturesAtPixel(evt.pixel);
              
                if (features?.length > 1) {
                    setTargetTemplate(features[0]?.values_?.id);
                    setDetailSwitch(true);
                }

                //setDetailSwitch(true);
            }
            map.on('singleclick', handler);

            return () => {
                map.un('singleclick', handler);
            }
        }
    }, [map])

    const createHlLayers = (callback) => {

        let yqLayer, hdLayer, skLayer;
        JcyjApi.jcdList().then(resp => {
            const features = resp.rows?.filter(row => {
                return row.geom
            })?.map(item => {
                return dataToFeature(item)
            })
            yqLayer = createLayer((feature) => {
                return new Style({
                    image: new Icon({
                        src: resourcePath.mapIcons.yq_blue,
                        scale: 0.7,
                        anchor: [0.5, 1]
                        // size: [60, 98],
                        // scale: 1 / 24
                    })
                })
            }, features?.filter(feature => feature.get('jcdlx') === '雨情') || []);
            yqLayer.set('layerName', '雨情')
            yqLayer.set('lxTitle', '雨情')
            yqLayer.set('type', 'specialMap')
            hdLayer = createLayer((feature) => {
                return new Style({
                    image: new Icon({
                        src: resourcePath.mapIcons.hd_blue,
                        scale: 0.7,
                        anchor: [0.5, 1]
                        // size: [60, 98],
                        // scale: 1 / 24
                    })
                })
            }, features?.filter(feature => feature.get('jcdlx') === '河道'));
            hdLayer.set('layerName', '河道')
            hdLayer.set('lxTitle', '河道')
            hdLayer.set('type', 'specialMap')
            skLayer = createLayer((feature) => {
                return new Style({
                    image: new Icon({
                        src: resourcePath.mapIcons.sk_blue,
                        // size: [30, 80],
                        scale: 0.7,
                        anchor: [0.5, 1]
                    })
                })
            }, features?.filter(feature => feature.get('jcdlx') === '水库'));
            skLayer.set('layerName', '水库')
            skLayer.set('lxTitle', '水库')
            skLayer.set('type', 'specialMap')
            callback?.([yqLayer, hdLayer, skLayer])
        });
    }
    const generateLegendDatas = () => {
        const allLayers = map.getLayers().getArray();
        const legendLayers = allLayers.filter(layer => {
            return layer.get('type') === 'specialMap';
        });
        setLegendDatas(legendLayers.map(layer => {
            // console.log('layer',layer)
            let kind = layer.get('layerName')
            return {
                name: layer.get('layerName'),
                // layer,
                // key: Math.random(),
                type: layer.get('type'),
                iconPath: resourcePath.iconMap[kind]
            }
        }))
    }

    const createHlLayersearthquake = (callback) => {

        let dzLayer;
        FxqyApi.lndzsj_find().then(resp => {
            //console.log('地震数据调试:', resp);
            const features = resp.rows?.filter(row => {
                if(row?.geom){
                    return row.geom
                }else if(row?.jd&&row?.wd){
                    return row.geom=`POINT(${row.jd} ${row.wd})`
                }else{
                    console.warn('该行不包含有效的几何数据或坐标:', row);
                    return false; // 返回 false，排除该行
                }
                //return row.geom
            })?.map(item => {
                return dataToFeature(item)
            })
            //console.log('地震数据调试地图元素:', features);
            dzLayer = createLayer((feature) => {
                // console.log('feature',feature)
                return new Style({
                    image: new Icon({
                        src: resourcePath.mapIcons.dze_yellow,
                        scale: 0.7,
                        anchor: [0.5, 1]
                        // size: [60, 98],
                        // scale: 1 / 24
                    })
                })
            }, features);
            dzLayer.set('layerName', '地震灾害')
            dzLayer.set('lxTitle', '地震')
            dzLayer.set('type', 'specialMap')
            dzLayer.setZIndex(9999)
            setLayers([dzLayer])
            callback?.([dzLayer])
        });
    }

    const createHlLayersGeologyDisaster = (callback) => {
        let geologyLayer, fireLayer, floodLayer, qxLayer;
        FxqyApi.yhlx_find1().then(resp => {
            console.log('yhlb',resp)
            //console.log(_.groupBy(resp.rows, 'yhlb'))
            //console.log(_.groupBy(resp.rows, 'yhlx'))
            const features = resp.rows?.filter(row => {
                //部分隐患数据没有geom，但是有经度（jd）纬度（wd）
                if(row.geom){
                    return row.geom
                }else if(row.geom===null&&row.jd!=null&&row.wd!=null){
                    row.geom=`POINT(${row.jd} ${row.wd})`
                }
                //console.log(row)
                return row.geom
            })?.map(item => {
                return dataToFeature(item)
            })
            geologyLayer = createLayer((feature) => {
                return new Style({
                    image: new Icon({
                        src: resourcePath.mapIcons.dzi_blue,
                        scale: 0.7,
                        anchor: [0.5, 1]
                        // size: [60, 98],
                        // scale: 1 / 24
                    })
                })
            }, features?.filter(feature => feature.get('yhlb') === '地质灾害') || []);
            geologyLayer.set('layerName', '地质灾害')
            geologyLayer.set('lxTitle', '地灾')
            geologyLayer.set('type', 'specialMap')
            geologyLayer.setZIndex(9999)
            fireLayer = createLayer((feature) => {
                return new Style({
                    image: new Icon({
                        src: resourcePath.mapIcons.zlhz_red,
                        scale: 0.7,
                        anchor: [0.5, 1]
                        // size: [60, 98],
                        // scale: 1 / 24
                    })
                })
            }, features?.filter(feature => feature.get('yhlb') === '火灾') || []);
            fireLayer.set('layerName', '森林火灾')
            fireLayer.set('lxTitle', '火灾')
            fireLayer.set('type', 'specialMap')
            fireLayer.setZIndex(9999)
            floodLayer = createLayer((feature) => {
                return new Style({
                    image: new Icon({
                        src: resourcePath.mapIcons.hl_org,
                        scale: 0.7,
                        anchor: [0.5, 1]
                        // size: [60, 98],
                        // scale: 1 / 24
                    })
                })
            }, features?.filter(feature => feature.get('yhlb') === '洪涝') || []);
            floodLayer.set('layerName', '洪涝灾害')
            floodLayer.set('lxTitle', '洪涝')
            floodLayer.set('type', 'specialMap')
            floodLayer.setZIndex(9999)
            qxLayer = createLayer((feature) => {
                return new Style({
                    image: new Icon({
                        src: resourcePath.mapIcons.qx_blue,
                        scale: 0.7,
                        anchor: [0.5, 1]
                    })

                })
            }, features?.filter(feature => feature.get('yhlb') === '气象') || []);
            qxLayer.set('layerName', '气象灾害')
            qxLayer.set('lxlTitle', '气象')
            qxLayer.set('type', 'specialMap')
            qxLayer.setZIndex(9999)
            setLayers([geologyLayer, fireLayer, floodLayer, qxLayer])


            callback?.([geologyLayer, fireLayer, floodLayer, qxLayer])
        });
    }
    const createWeature = (callback) => {
        let qxLayer;
        FxqyApi.yhlx_find().then(resp => {
            const features = resp.rows?.filter(row => {
                //console.log(row)
                return row.geom
            })?.map(item => {
                return dataToFeature(item)
            })
            qxLayer = createLayer((feature) => {
                return new Style({
                    src: resourcePath.mapIcons.qx_blue,
                    scale: 0.7,
                    anchor: [0.5, 1]
                })
            }, features?.filter(feature => feature.get('yhlb') === '气象') || []);
            qxLayer.set('layerName', '气象')
            qxLayer.set('lxlTitle', '气象')
            qxLayer.set('type', 'specialMap')
            callback?.([qxLayer])

        })
    }


    const [dzengDetailItem, setDzengDetailItem] = useState(false);
    const [showDziDetailItem, setShowDziDetailItem] = useState(false);
    const [hlDetailItem, setHlDetailItem] = useState(false);
    const [zlDetailItem, setZlDetailItem] = useState(false);
    const [detailItem, setDetailItem] = useState();
    PubSub.subscribe("detailItem", (_, data) => {
        setDetailItem(data.detailItem)
        //console.log('detailItem',data);
    })

    const [title, setTitle] = useState();
    const popupRef = useRef();
    useEffect(() => {
        if (map) {
            const handler = evt => {
                const popup = new Overlay({
                    element: popupRef.current,
                });
                map.addOverlay(popup);
                const features = map.getFeaturesAtPixel(evt.pixel);
                // console.log('features',features)
                const item = features?.find(feature => feature.get('jcdlx'))?.getProperties();
                const coordinate = features?.find(feature => feature.get('jcdlx'))?.getGeometry()?.getCoordinates();

                const item1 = features?.find(feature => feature.get('yhlb'))?.getProperties();
                const coordinate1 = features?.find(feature => feature.get('yhlb'))?.getGeometry()?.getCoordinates();

                if (coordinate) {
                    popup.setPosition(coordinate);
                } else {
                    popup.setPosition(coordinate1)
                }

                const tooltip = item?.zdm;
                const tooltip1 = item1?.yhmc;
                if (tooltip) {
                    setTitle(tooltip);
                } else {
                    setTitle(tooltip1);
                }
                let popover = bootstrap.Popover.getInstance(popupRef.current);
                if (popover) {
                    popover.dispose();
                }
                popover = new bootstrap.Popover(popupRef.current, {
                    animation: false,
                    container: popupRef.current,
                    content: null,
                    html: true,
                    placement: 'right'
                });
                popover.show();
            }
            map.on('pointermove', handler);
            return () => {
                map.un('pointermove', handler);
            }
        }
    }, [map])

    return <>
        <FxqhContext.Provider value={{
            detailSwitch,
            StatisticAndListSwitch,
            leftKey,
            rowData,
            disasterType,
            targetTemplate,
            setJyl,
            setDetailSwitch,
            setStatisticAndListSwitch,
            //setLeftKey:data=>setLeftKey(data),
            setRowData,
            setTargetTemplate,
            setSelectedName,
            selectedName,
        }}>
            <div className='layout-v' style={{
                position: "absolute",
                left: 20,
                top: 20,
                bottom: 20,
                overflow: 'auto'
            }}>
                {!visible && <DarkBtn placement="right" title="专题地图" icon={<MenuUnfoldOutlined />} onClick={e => {
                    setVisible(true)
                }}></DarkBtn>}
                {visible && <>
                    <DarkCard className="layout-h center" style={{
                        width: 300,
                        // height: 42,
                        marginBottom: 10,
                        fontSize: 20,
                        fontWeight: 'bold',
                    }}>
                        <div className='fill'>专题地图</div>
                        <Button title="收起" icon={<MenuFoldOutlined />} type={'text'} onClick={e => {
                            setVisible(false)
                        }}></Button>
                    </DarkCard>
                    <DarkCard className="fill h0" style={{
                        width: 300,
                        overflow: "auto"
                        // height: 300
                    }}>
                        <Menu theme='dark' onClick={({ key }) => {

                            setSelectedName(key)

                            const allLayers = map.getLayers().getArray();
                            [...allLayers].forEach(l => {
                                if (l?.get?.('type') === 'specialMap') {
                                    map.removeLayer(l);
                                }
                            })
                            createBaseLayers(baseLayers => {
                                baseLayers.forEach(l => {
                                    l.set('type', 'specialMap')
                                    //map.addLayer(l)

                                })
                                
                                setStatisticAndListSwitch(true);
                                setLeftKey(key);
                                switch (key) {
                                    case '1':
                                        createHlLayersearthquake(l => {
                                            l.forEach(l => {
                                                l.set('type', 'specialMap')

                                                map.addLayer(l)
                                            })
                                            generateLegendDatas();
                                        })
                                        setDisasterType(['地震灾害']);
                                        break;
                                    case '2':
                                        createHlLayersGeologyDisaster(l => {
                                            l.forEach(l => {
                                                l.set('type', 'specialMap')
                                                if (l?.get?.('layerName') === '地质灾害')
                                                    map.addLayer(l)
                                            })
                                            generateLegendDatas();
                                        })
                                        setDisasterType(["地质灾害"]);
                                        break;
                                    case '3':
                                        createHlLayersGeologyDisaster(l => {
                                            l.forEach(l => {
                                                l.set('type', 'specialMap')
                                                if (l?.get?.('layerName') === '气象灾害')
                                                    map.addLayer(l)
                                            })
                                            generateLegendDatas();
                                        })
                                        setDisasterType(["气象灾害"]);
                                        break;
                                    case '4':
                                        createHlLayersGeologyDisaster(l => {
                                            l.forEach(l => {
                                                l.set('type', 'specialMap')
                                                if (l?.get?.('layerName') === '洪涝灾害')
                                                    map.addLayer(l)
                                            })
                                            generateLegendDatas();
                                            // console.log('火灾',l)
                                        })
                                        setDisasterType(["洪涝灾害"]);
                                        break;
                                    case '5':
                                        createHlLayersGeologyDisaster(l => {
                                            l.forEach(l => {
                                                l.set('type', 'specialMap')
                                                if (l?.get?.('layerName') === '森林火灾')
                                                    map.addLayer(l)
                                            })
                                            generateLegendDatas();
                                            // console.log('火灾',l)
                                        })
                                        setDisasterType(["森林火灾"]);
                                        break;
                                    default:
                                }
                            });

                        }} items={[{
                            key: '1',
                            label: '地震灾害风险区划',

                        }, {
                            type: 'divider'
                        }, {
                            key: '2',
                            label: '地质灾害风险区划'
                        }, {
                            type: 'divider'
                        }, {
                            key: '3',
                            label: '气象灾害风险区划'
                        }, {
                            type: 'divider'
                        }, {
                            key: '4',
                            label: '洪涝灾害风险区划'
                        }, {
                            type: 'divider'
                        }, {
                            key: '5',
                            label: '林竹火灾风险区划'
                        }]}></Menu>
                    </DarkCard>
                </>}

            </div>

            {/* {legendDatas?.length && <Example datas={legendDatas} onVisibleChange={(checked, type, data) => {
                layers.find(layer => layer.get('layerName') === data?.name)?.set('visible', checked)
                // layers?.set('visible', checked)
            }} />} */}
            <Example datas={[{
                name: '地震灾害',
                type: 'specialMap',
                iconPath: resourcePath.mapIcons.dze_yellow
            }, {
                name: '地质灾害',
                type: 'specialMap',
                iconPath: resourcePath.mapIcons.dzi_blue
            }, {
                name: '气象灾害',
                type: 'specialMap',
                iconPath: resourcePath.mapIcons.qx_blue
            }, {
                name: '洪涝灾害',
                type: 'specialMap',
                iconPath: resourcePath.mapIcons.hl_org
            }, {
                name: '森林火灾',
                type: 'specialMap',
                iconPath: resourcePath.mapIcons.zlhz_red
            }]} onVisibleChange={(checked, type, data) => {
                layers.find(layer => layer.get('layerName') === data?.name)?.set('visible', checked)
                // layers?.set('visible', checked)
            }} 
            fxqh={1}/>
            {StatisticAndListSwitch && !detailItem && <StatisticAndList />}
            {detailSwitch && !detailItem && <DisasterDetails onClose={e => { setDetailSwitch(false) }} />}
            {/* {detailSwitch &&  <DisasterDetails onClose={e => { setDetailSwitch(false) }} />} */}
            {/* {!zlDetailItem && !hlDetailItem && !showDziDetailItem && dzengDetailItem &&  <Lndzsjlb  dzengDetailItem={dzengDetailItem} />}
        {!zlDetailItem && !hlDetailItem && !dzengDetailItem && showDziDetailItem &&  <Yhdzzt />}
        {!zlDetailItem && !showDziDetailItem && !dzengDetailItem && hlDetailItem && <Yhhltb /> }
        {!dzengDetailItem && !hlDetailItem && !showDziDetailItem && zlDetailItem &&  <Yhslhz />} */}
            {title && <Popup title={title} ref={popupRef} position={position} />}
        </FxqhContext.Provider>

    </>;
}